// chat.js - AI聊天页面

// 导入所需的管理器
const storageManager = require('../../../manager/storageManager').getInstance();
const wordDataManager = require('../../../manager/wordDataManager').getInstance();
const managerFactories = require('../../../manager/index');

// 获取管理器实例
const aiManager = managerFactories.aiManager();
const wordLearningDataManager = managerFactories.wordLearningDataManager();

const app = getApp();
const marked = require('../../../utils/marked.js');
const util = require('../../../utils/util');

Page({
  data: {
    messages: [],
    inputValue: '',
    loading: false,
    lastMessageId: '',
    scrollToMessageId: '', // 用于控制滚动到特定消息
    showWordModal: false,
    learnedWords: [],
    selectedWords: [],
    currentBookInfo: null,
    debugMode: false, // 调试模式，设置为true可以显示调试信息
    userScrolled: false, // 标记用户是否手动滚动
    hasStartedAIResponse: false, // 标记AI是否已经开始响应
    touchStartY: 0, // 触摸开始时的Y坐标
    touchEndY: 0, // 触摸结束时的Y坐标
    // isUserTouching: false // 标记用户是否正在触摸
  },

  onLoad: function(options) {
    // 配置marked选项
    marked.setOptions({
      breaks: true,
      gfm: true,
      headerIds: false
    });
    // 从选项中获取词书ID
    this.bookId = options.bookId || wordDataManager.getActiveBookId();
    this.loadChatHistory();
    this.loadLearnedWords();
    this.loadCurrentBookInfo();
  },
  


  onShow: function() {
    // 页面显示时更新已学习单词列表
    this.loadLearnedWords();
  },

  /**
   * 生成播放语音图标HTML
   */
  getAudioHtml(msg) {
    return `<img class="play-audio-icon" src="/images/voice.png" data-action="play-audio" data-msg-id="${msg.id}" style="width: 20px; height: 20px; margin-left: 5px; vertical-align: middle;user-select: none;" />`
  },

  /**
   * 加载聊天历史
   */
  loadChatHistory: function() {
    try {
      const history = storageManager.getStorage(storageManager.STORAGE_KEYS.AI_CHAT_HISTORY) || [];
      
      // 加载时动态生成towxmlContent
      const messagesWithContent = history.map(msg => {
        let htmlContent = marked(msg.content || '') + (msg.content ? this.getAudioHtml(msg) : '');
        htmlContent = this.highlightWordsInHtml(htmlContent, msg.selectedWords);
        return {
          ...msg,
          htmlContent: htmlContent,
          htmlTranslation: marked(msg.translation || ''),
          htmlPhrasesExplanations: marked(msg.phrasesExplanations || ''),
        }
      });
      
      this.setData({
        messages: messagesWithContent
      });
      if (messagesWithContent.length > 0) {
        this.setData({
          lastMessageId: messagesWithContent[messagesWithContent.length - 1].id
        });
      }
    } catch (error) {
      console.error('加载聊天历史失败:', error);
    }
  },

  /**
   * 保存聊天历史
   */
  saveChatHistory: function() {
    try {
      // 移除towxmlContent字段后再保存
      const selectedWordObjects = this.getSelectedWordObjects();
      const messagesToSave = this.data.messages.map(msg => {
        const { htmlContent, htmlTranslation, htmlPhrasesExplanations, hasPhrasesExplanations, hasTranslation,  ...rest } = msg;
        const words = selectedWordObjects.map(word => word.english).filter(word => word && word.trim());
        return {
          ...rest,
          selectedWords: words || []
        };
      });
      storageManager.setStorage(storageManager.STORAGE_KEYS.AI_CHAT_HISTORY, messagesToSave);
    } catch (error) {
      console.error('保存聊天历史失败:', error);
    }
  },

  /**
   * 加载当前词书信息
   */
  loadCurrentBookInfo: function() {
    if (!this.bookId) return;
    
    const book = wordDataManager.getBookById(this.bookId);
    if (book) {
      this.setData({
        currentBookInfo: book
      });
    }
  },

  /**
   * 加载已学习的单词
   */
  loadLearnedWords: function() {
    if (!this.bookId) return;
    
    try {
      // 获取词书中的所有单词
      const bookWords = wordDataManager.getWordsByBookId(this.bookId);
      
      // 过滤出已学习的单词
      const learnedWords = bookWords.filter(word => {
        const learnCount = wordLearningDataManager.getWordLearnCount(word.id);
        return learnCount > 0;
      });
      
      // 初始化带有选中状态的单词列表
      const wordsWithSelection = learnedWords.map(word => ({
        ...word,
        isSelected: false
      }));
      
      this.setData({
        learnedWords: learnedWords,
        wordsWithSelection: wordsWithSelection
      });
    } catch (error) {
      console.error('加载已学习单词失败:', error);
    }
  },

  /**
   * 监听输入变化
   */
  onInput: function(e) {
    this.setData({
      inputValue: e.detail.value
    });
  },

   /**
   * 处理富文本中的图片点击事件
   */
  onImgTap: function(e) {
    const imgData = e.detail;
    // 检查是否是播放音频的图标
    if (imgData['data-action'] === 'play-audio') {
      const msgId = imgData['data-msg-id'];
      // 查找对应的消息
      const msg = this.data.messages.find(m => m.id === msgId);
      if (msg && msg.content) {
        this.playOriginalText({currentTarget: {dataset: {text: msg.content}}});
      }
    }
  },

   /**
   * 播放原文语音
   */
  playOriginalText: function(e) {
    const markdownText = e.currentTarget.dataset.text;
    const audioManager = app.getAudioManager();
    if (markdownText) {
      // 将Markdown转换为纯文本
      const plainText = util.stripMarkdown(markdownText, true);
      // 移除中文内容，只保留英文
      const englishOnlyText = util.removeChinese(plainText);
      // 调用音频管理器播放文本，使用英文发音
      audioManager.playTextToSpeech(englishOnlyText, 1.0, 'en');
    }
  },

  /**
   * 发送消息
   */
  sendMessage: function() {
    const content = this.data.inputValue.trim();
    if (!content || this.data.loading) return;
    
    // 创建用户消息
    const userMessage = {
      id: 'msg_' + Date.now() + '_user',
      role: 'user',
      content: content,
      timestamp: new Date().toISOString()
    };
    
    // 添加用户消息到列表
    const messages = [...this.data.messages, userMessage];
    this.setData({
      messages: messages,
      inputValue: '',
      loading: true,
      lastMessageId: userMessage.id,
      scrollToMessageId: '', // 重置滚动消息ID
      userScrolled: false, // 重置用户滚动状态
      hasStartedAIResponse: false // 重置AI响应状态
    });
    
    // 保存聊天历史
    this.saveChatHistory();
    
    // 创建AI消息占位符
    const aiMessageId = 'msg_' + Date.now() + '_ai';
    const aiMessage = {
      id: aiMessageId,
      role: 'ai',
      content: '',
      translation: '',
      phrasesExplanations: '',
      htmlContent: null,
      htmlTranslation: null,
      htmlPhrasesExplanations: null,
      hasTranslation: false,
      hasPhrasesExplanations: false,
      timestamp: new Date().toISOString()
    };
    
    messages.push(aiMessage);
    this.setData({
      messages: messages,
      lastMessageId: aiMessageId
    });
    
    // 调用AI API获取回复
    this.getAIResponse(content, (chunk) => {
      this.updateAIMessageByChunk(aiMessageId, chunk);
    }).then(() => {
      // 处理AI返回的内容，检查translation字段是否包含短语解释
      this.processAIResponseFinal(aiMessageId);
      this.setData({ loading: false });
      this.saveChatHistory();
    }).catch((error) => {
      console.error('获取AI回复失败:', error);
      this.handleAIResponseError(aiMessageId);
    });
  },

  /**
   * 更新AI消息内容（流式处理）
   */
  updateAIMessageByChunk: function(aiMessageId, chunk) {
    const updatedMessages = [...this.data.messages];
    const aiMsgIndex = updatedMessages.findIndex(msg => msg.id === aiMessageId);
    if (aiMsgIndex === -1) return;
    
    const aiMsg = updatedMessages[aiMsgIndex];
    // 在流式处理阶段，所有内容都更新到content字段
    if (!aiMsg.content) aiMsg.content = '';
    aiMsg.content += chunk;
    
    // 只更新content的HTML内容，实时显示
    aiMsg.htmlContent = marked(aiMsg.content);
    
    this.setData({
      messages: updatedMessages,
      hasStartedAIResponse: true // 标记AI已开始响应
    });
    
    // 如果用户没有手动滚动，则自动滚动到底部
    if (!this.data.userScrolled) {
      // 使用setTimeout确保DOM已更新
      setTimeout(() => {
        this.scrollToBottom();
      }, 50);
    }
  },
  
  /**
   * 滚动到底部
   */
  scrollToBottom: function() {
    try {
      // 直接使用setData来更新scroll-into-view
      // 这是最可靠的方式，因为我们已经在WXML中绑定了scroll-into-view="msg-{{lastMessageId}}"
      // 我们需要强制重新渲染以触发滚动
      const tempId = this.data.lastMessageId;
      // 先设置一个不同的值，然后在下一个事件循环中设置回正确的值
      this.setData({ scrollToMessageId: '' });
      
      setTimeout(() => {
        this.setData({
          scrollToMessageId: tempId
        });
      }, 0);
    } catch (error) {
      console.log('滚动到底部失败:', error);
    }
  },
  
  /**
   * 处理触摸开始事件
   */
  // onTouchStart: function(e) {
  //   // 记录触摸开始位置
  //   this.setData({
  //     touchStartY: e.touches[0].clientY,
  //     isUserTouching: true
  //   });
  // },

  /**
   * 处理触摸结束事件
   */
  // onTouchEnd: function() {
  //   this.setData({
  //     isUserTouching: false
  //   });
  // },

  /**
   * 处理触摸移动事件
   */
  // onTouchMove: function(e) {
  //   // 记录触摸移动位置
  //   this.setData({
  //     touchEndY: e.touches[0].clientY
  //   });
  // },

  /**
   * 处理滚动事件
   */
  // onScroll: function(e) {
  //     console.log('滚动事件:', e.detail);
  //     // 使用选择器查询获取scroll-view的实际高度
  //     const query = wx.createSelectorQuery();
  //     query.select('.chat-messages').boundingClientRect();
  //     query.exec(res => {
  //       if (res && res[0]) {
  //         const actualClientHeight = res[0].height;
  //         // 获取滚动位置，添加安全检查
  //         const scrollHeight = Number(e.detail.scrollHeight) || 0;
  //         const scrollTop = Number(e.detail.scrollTop) || 0;
  //         const scrollViewHeight = scrollHeight - actualClientHeight;
          
  //         console.log('实际scroll-view高度:', actualClientHeight, 'scrollHeight:', scrollHeight, 'scrollViewHeight:', scrollViewHeight, 'scrollTop:', scrollTop);
          
  //         // 继续处理滚动逻辑
  //         this.handleScrollLogic(scrollViewHeight, scrollTop, actualClientHeight);
  //       }
  //     });
      
  // },
  
  /**
   * 处理滚动逻辑
   */
  // handleScrollLogic: function(scrollViewHeight, scrollTop, clientHeight) {
  //     // 如果用户正在触摸，认为是手动滚动
  //     if (this.data.isUserTouching) {
  //       // 计算触摸滑动距离
  //       const touchDiff = this.data.touchStartY - this.data.touchEndY;
        
  //       // 如果有明显的触摸滑动距离，或者滚动位置距离底部超过50像素，则认为用户手动滚动了
  //       if (Math.abs(touchDiff) > 10 || (scrollViewHeight - scrollTop) > 50) {
  //         this.setData({ userScrolled: true });
  //       }
  //     }
      
  //     // 如果用户滚动回到底部，则重置滚动状态
  //     if (scrollViewHeight - scrollTop <= 50) {
  //       this.setData({
  //         userScrolled: false
  //       });
  //     }
  // },

  /**
   * 处理AI返回的最终内容
   */
  processAIResponseFinal: function(aiMessageId) {
    const updatedMessages = [...this.data.messages];
    const aiMsgIndex = updatedMessages.findIndex(msg => msg.id === aiMessageId);
    if (aiMsgIndex === -1) return;
    
    const aiMsg = updatedMessages[aiMsgIndex];
    const fullResponse = aiMsg.content || '';
    
    // 初始化默认值
    let content = '';
    let translation = '';
    let phrasesExplanations = '';
    
    // 检查内容类型并进行相应解析
    if (fullResponse.includes('**English Version:**')) {
      // 处理短文格式
      // 提取英文原文部分
      const englishVersionRegex = /\*\*English Version:\*\*(.*?)(?=\*\*中文翻译：\*\*|\*\*重要短语|$)/s;
      const englishMatch = fullResponse.match(englishVersionRegex);
      content = englishMatch ? englishMatch[1].trim() : '';
    } else if (fullResponse.includes('**内容：**')) {
      // 处理普通聊天格式 - 有明确内容标记
      const contentRegex = /\*\*内容：\*\*(.*?)(?=\*\*中文翻译：\*\*|\*\*重要短语|$)/s;
      const contentMatch = fullResponse.match(contentRegex);
      content = contentMatch ? contentMatch[1].trim() : '';
    } else {
      // 处理无明确标记的格式 - 使用原始逻辑
      const translationRegex = /(.*?)(?:\n|\r\n)*\*\*中文翻译：\*\*(.*?)(?:\n|\r\n)*(?:\*\*重要短语|$)/s;
      const translationMatch = fullResponse.match(translationRegex);
      
      if (translationMatch) {
        // 提取原文部分
        content = translationMatch[1].trim();
      }
    }
    
    // 提取中文翻译部分（通用格式）
    const translationRegex = /\*\*中文翻译：\*\*(.*?)(?=\*\*重要短语|$)/s;
    const translationMatch = fullResponse.match(translationRegex);
    if (translationMatch) {
      let translationContent = translationMatch[1].trim();
      
      // 检查翻译部分是否包含短语解释
      const phrasesInTranslationRegex = /(.*?)(?:\n|\r\n)*---(?:\n|\r\n)*\*\*重要短语(?:\/|或)句型解释：\*\*(.*)/s;
      const phrasesInTranslationMatch = translationContent.match(phrasesInTranslationRegex);
      
      if (phrasesInTranslationMatch) {
        // 提取翻译部分和短语解释部分
        translationContent = phrasesInTranslationMatch[1].trim();
        phrasesExplanations = phrasesInTranslationMatch[2].trim();
      }
      
      // 删除翻译内容中的"---"分隔符
      translation = translationContent.replace(/\n---\n/g, '\n').replace(/\r\n---\r\n/g, '\r\n').replace(/---/g, '');
    }
    
    // 如果还没有提取到短语解释，尝试直接提取（通用格式）
    if (!phrasesExplanations) {
      const phrasesRegex = /\*\*重要短语(?:\/|或)句型解释：\*\*(.*?)$/s;
      const phrasesMatch = fullResponse.match(phrasesRegex);
      if (phrasesMatch) {
        phrasesExplanations = phrasesMatch[1].trim();
      }
    }
    
    // 如果内容还是空的（未匹配到任何格式），则使用完整响应
    if (!content) {
      content = fullResponse;
    }
    
    // 更新消息对象的各个字段
    aiMsg.content = content;
    aiMsg.translation = translation;
    aiMsg.phrasesExplanations = phrasesExplanations;
    
    // 更新HTML内容和标志位
    this.updateMessageHTMLContent(aiMsg);
    
    this.setData({
      messages: updatedMessages
    });
  },

  /**
   * 处理AI回复错误
   */
  handleAIResponseError: function(aiMessageId) {
    const updatedMessages = [...this.data.messages];
    const aiMsgIndex = updatedMessages.findIndex(msg => msg.id === aiMessageId);
    if (aiMsgIndex !== -1) {
      updatedMessages[aiMsgIndex].content = '抱歉，AI服务暂时不可用，请稍后再试。';
      updatedMessages[aiMsgIndex].htmlContent = marked(updatedMessages[aiMsgIndex].content);
      this.setData({
        messages: updatedMessages,
        loading: false
      });
      this.saveChatHistory();
    }
  },

  /**
   * 更新消息的HTML内容和标志位
   */
  updateMessageHTMLContent: function(message) {
    // 首先将Markdown转换为HTML
    let htmlContent = marked(message.content) + (message.content ? this.getAudioHtml(message) : '');
    
    // 如果有选中的单词，对其进行高亮处理
    if (this.data.selectedWords && this.data.selectedWords.length > 0) {
      // 获取选中单词的详细信息
      const selectedWordObjects = this.getSelectedWordObjects();
      const words = selectedWordObjects.map(word => word.english).filter(word => word && word.trim());
      
      // 提取英文单词并进行高亮处理
      if (selectedWordObjects.length > 0) {
        htmlContent = this.highlightWordsInHtml(htmlContent, words);
      }
    }
    
    message.htmlContent = htmlContent;
    message.htmlTranslation = marked(message.translation);
    message.htmlPhrasesExplanations = marked(message.phrasesExplanations);
    message.hasTranslation = message.translation !== '';
    message.hasPhrasesExplanations = message.phrasesExplanations !== '';
  },
  
  /**
   * 获取选中单词的详细信息对象
   * @param {Array} selectedWordIds - 可选，指定的单词ID数组，如果不提供则使用当前选中的单词
   * @returns {Array} - 选中单词的对象数组
   */
  getSelectedWordObjects: function(selectedWordIds) {
    // 如果提供了selectedWordIds参数则使用它，否则使用当前选中的单词ID
    const wordIds = selectedWordIds || this.data.selectedWords;
    return this.data.learnedWords.filter(word => 
      wordIds.includes(word.id)
    );
  },
  
  /**
   * 在HTML内容中高亮显示指定的单词
   * @param {string} html - HTML内容
   * @param {Array} words - 要高亮的单词对象数组
   * @returns {string} - 高亮处理后的HTML内容
   */
  highlightWordsInHtml: function(html, words) {
    if (!words?.length) return html;
    
    // 构建正则表达式，匹配完整的单词，不区分大小写
    // 使用单词边界\b确保只匹配完整的单词
    const wordsRegex = new RegExp(
      '(\\b)(' + 
      words.map(word => {
        // 转义特殊字符，确保正则表达式安全
        return word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
      }).join('|') + 
      ')(\\b)', 
      'gi'
    );
    
    // 使用正则表达式替换匹配的单词，用span标签包裹并添加高亮样式
    // 使用捕获组保留单词边界
    return html.replace(wordsRegex, '$1<span style="background-color: #e2dcef; padding: 0 4px; border-radius: 2px;">$2</span>$3');
  },

  /**
   * 获取AI回复
   */
  getAIResponse: function(content, onChunk) {
    // 准备消息历史
    const messageHistory = this.data.messages.slice(-10).map(msg => ({
      role: msg.role,
      content: msg.content
    }));
    
    // 添加系统提示
    const messages = [
      {
        role: 'system',
        content: '你是一位专业的英语学习助手，擅长帮助学生学习英语，提供准确、有用的解答。'
      },
      ...messageHistory
    ];
    
    // 调用AI管理器发送消息
    return aiManager.sendMessage(messages, onChunk);
  },

  /**
   * 显示单词选择弹窗
   */
  showWordSelection: function() {
    // 检查AI调用次数限制
    if (app.globalData.userInfo.callAICount >= aiManager.userMaxCallAICount) {
      wx.showToast({
        title: 'AI调用次数已达上限',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    // 检查是否有词书ID
    if (!this.bookId) {
      wx.showToast({
        title: '请先选择一个词书',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    // 检查已学习单词数量
    const learnedCount = this.data.learnedWords.length;
    if (learnedCount < 5) {
      wx.showToast({
        title: `当前词书已学习单词不足5个，已学习${learnedCount}个`,
        icon: 'none',
        duration: 3000
      });
      return;
    }
    
    // 为每个单词添加选中状态
    const wordsWithSelection = this.data.learnedWords.map(word => ({
      ...word,
      isSelected: false
    }));
    
    // 显示弹窗并重置状态
    this.setData({
      showWordModal: true,
      selectedWords: [],
      isLimitWarning: false,
      wordsWithSelection: wordsWithSelection
    });
  },

  /**
   * 隐藏单词选择弹窗
   */
  hideWordModal: function() {
    this.setData({
      showWordModal: false
    });
  },

  /**
   * 切换单词选择状态
   */
  toggleWordSelection: function(e) {
    // 获取单词ID并确保是字符串类型，避免类型不匹配
    const wordId = String(e.currentTarget.dataset.id);
    
    // 获取当前选中的单词数组和单词列表
    const selectedWords = [...(this.data.selectedWords || [])];
    let wordsWithSelection = [...(this.data.wordsWithSelection || [])];
    let isLimitWarning = false;
    
    // 检查当前单词是否已选中
    const index = selectedWords.findIndex(id => id === wordId);
    
    if (index !== -1) {
      // 取消选中
      selectedWords.splice(index, 1);
      // 更新单词的选中状态
      wordsWithSelection = wordsWithSelection.map(word => 
        word.id === wordId ? { ...word, isSelected: false } : word
      );
    } else {
      // 如果未选中且未达到最大选择数量，则选中
      if (selectedWords.length < 20) {
        selectedWords.push(wordId);
        // 更新单词的选中状态
        wordsWithSelection = wordsWithSelection.map(word => 
          word.id === wordId ? { ...word, isSelected: true } : word
        );
      } else {
        // 显示选择数量限制警告
        wx.showToast({
          title: '最多只能选择20个单词',
          icon: 'none',
          duration: 1500
        });
        isLimitWarning = true;
      }
    }
    
    // 更新数据
    this.setData({
      selectedWords: selectedWords,
      isLimitWarning: isLimitWarning,
      wordsWithSelection: wordsWithSelection
    });
    
    // 清除警告状态
    if (isLimitWarning) {
      setTimeout(() => {
        this.setData({ isLimitWarning: false });
      }, 2000);
    }
  },

  /**
   * 确认单词选择并生成短文
   */
  confirmWordSelection: function() {
    const selectedWordIds = this.data.selectedWords;
    
    // 验证选择数量
    if (selectedWordIds.length < 5 || selectedWordIds.length > 20) {
      wx.showToast({
        title: '请选择5-20个单词',
        icon: 'none'
      });
      return;
    }
    
    // 重置滚动状态
    this.setData({
      scrollToMessageId: '', // 重置滚动消息ID
      userScrolled: false,
      hasStartedAIResponse: false
    });
    
    // 获取选中的单词信息
    const selectedWordObjects = this.getSelectedWordObjects(selectedWordIds);
    
    // 获取词书信息
    const bookInfo = this.data.currentBookInfo;
    const schoolStage = bookInfo?.schoolStage || '小学';
    const grade = bookInfo?.grade || '三年级';
    
    // 隐藏弹窗
    this.hideWordModal();
    
    // 创建用户消息（显示选中的单词）
    const selectedWordsText = selectedWordObjects.map(w => w.english).join(', ');
    const userMessage = {
      id: 'msg_' + Date.now() + '_user',
      role: 'user',
      content: `请用这些单词写一篇短文：${selectedWordsText}`,
      timestamp: new Date().toISOString()
    };
    
    // 添加用户消息到列表
    const messages = [...this.data.messages, userMessage];
    this.setData({
      messages: messages,
      loading: true,
      lastMessageId: userMessage.id
    });
    
    // 保存聊天历史
    this.saveChatHistory();
    
    // 创建AI消息占位符
    const aiMessageId = 'msg_' + Date.now() + '_ai';
    const aiMessage = {
      id: aiMessageId,
      role: 'ai',
      content: '',
      translation: '',
      phrasesExplanations: '',
      htmlContent: null,
      htmlTranslation: null,
      htmlPhrasesExplanations: null,
      hasTranslation: false,
      hasPhrasesExplanations: false,
      timestamp: new Date().toISOString()
    };
    
    messages.push(aiMessage);
    this.setData({
      messages: messages,
      lastMessageId: aiMessageId
    });
    
    // 调用AI生成短文
    aiManager.generateEssay(selectedWordObjects, schoolStage, grade, (chunk) => {
      // 复用相同的流式更新逻辑
      this.updateAIMessageByChunk(aiMessageId, chunk);
    }).then(() => {
      // 复用相同的最终处理逻辑
      this.processAIResponseFinal(aiMessageId);
      
      // 更新AI调用次数
      const cloudManager = app.globalData.cloudManager || app.getCloudManager();
      if (cloudManager) {
        cloudManager.updateUserInfo({ incrementCallAICount: true }).then(() => {
          console.log('AI调用次数更新成功');
          app.updateUserInfoInGlobal({
            ...app.globalData.userInfo,
            callAICount: (app.globalData.userInfo.callAICount || 0) + 1
          })
        }).catch(err => {
          console.error('更新AI调用次数失败:', err);
        });
      }
      
      this.setData({ loading: false });
      this.saveChatHistory();
    }).catch((error) => {
      console.error('生成短文失败:', error);
      
      // 更新AI消息显示错误信息
      const updatedMessages = [...this.data.messages];
      const aiMsgIndex = updatedMessages.findIndex(msg => msg.id === aiMessageId);
      if (aiMsgIndex !== -1) {
        updatedMessages[aiMsgIndex].content = '抱歉，生成短文失败，请稍后再试。';
        this.setData({
          messages: updatedMessages,
          loading: false
        });
        this.saveChatHistory();
      }
    });
  },

  /**
   * 检查文本是否包含中文字符
   * @private
   */
  _containsChineseCharacters(text) {
    // 中文正则表达式
    const chineseRegex = /[\u4e00-\u9fa5]/;
    // 统计中文和非中文字符数量
    let chineseCount = 0;
    let totalCount = 0;
    
    for (let i = 0; i < text.length; i++) {
      if (chineseRegex.test(text[i])) {
        chineseCount++;
      }
      totalCount++;
    }
    
    // 如果超过30%的字符是中文，则认为包含中文
    return chineseCount / totalCount > 0.3;
  },
  
  /**
   * 复制消息内容
   */
  copyMessage(e) {
    const messageId = e.currentTarget.dataset.id;
    const type = e.currentTarget.dataset.type || 'original';
    const message = this.data.messages.find(msg => msg.id === messageId);
    
    if (message) {
      let textToCopy = message.content;
      let successTitle = '复制成功';
      
      if (type === 'translation' && message.translation) {
        textToCopy = message.translation;
        successTitle = '译文复制成功';
      } else if (type === 'phrases' && message.phrasesExplanations) {
        textToCopy = message.phrasesExplanations;
        successTitle = '解释复制成功';
      }
      
      wx.setClipboardData({
        data: textToCopy,
        success: () => {
          wx.showToast({
            title: successTitle,
            icon: 'success',
            duration: 2000
          });
        },
        fail: () => {
          wx.showToast({
            title: '复制失败',
            icon: 'none',
            duration: 2000
          });
        }
      });
    }
  },
  


  /**
   * 处理滚动到底部事件
   */
  onScrollToLower: function(e) {
    // 添加安全检查以避免潜在的NaN问题
    const scrollHeight = e.detail ? Number(e.detail.scrollHeight) || 0 : 0;
    const clientHeight = e.detail ? Number(e.detail.clientHeight) || 0 : 0;
    const scrollViewHeight = scrollHeight - clientHeight;
    
    console.log('onScrollToLower triggered with scrollViewHeight:', scrollViewHeight);
    
    // 当滚动到底部时，重新开启自动滚动
    this.setData({
      userScrolled: false
    });
  }
});